<template>
  <div class="content">
    <div class="content-table">
      <div class="content-table--wrap">
        <div class="user-tree">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            style="overflow: auto"
          />
        </div>

        <div class="table-left">
          <div class="table-left--header">
            <el-input
              clearable
              placeholder="输入姓名查询"
              style="margin-right: 10px"
              v-model="formInline.nameLike"
            ></el-input>
            <el-button
              class="table-left--btn"
              type="primary"
              @click="handleSearch"
              >查询</el-button
            >
          </div>

          <div class="table-box">
            <div class="flex-box">
              <i class="icon snowfont icon-daixuan"></i>
              <p>待选人员</p>
            </div>
            <el-table
              border
              key="table-left"
              @select="handleSelectionChange"
              @select-all="handleSelectionAll"
              ref="multipleTable"
              :data="userList"
              stripe
              style="width: 100%"
              :height="370"
              :header-cell-style="{
                background: '#F7F9FD',
                color: '#000'
              }"
              :row-key="getRowKeys"
            >
              <template #empty>
                <el-empty :image-size="150" description="暂无数据"></el-empty>
              </template>
              <el-table-column
                type="selection"
                :reserve-selection="true"
                width="50"
              />
              <el-table-column
                prop="name"
                label="姓名"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="userName"
                label="用户名"
                show-overflow-tooltip
              ></el-table-column>
            </el-table>
          </div>

          <div class="table-left--footer">
            <re-pagination
              :layout="`total, prev, pager, next`"
              :total="total"
              v-model:page="formInline.pageNum"
              v-model:limit="formInline.pageSize"
              @pagination="handleSearch"
              :background="false"
            />
          </div>
        </div>

        <div class="table-right">
          <div class="table-right--header">
            <p>已选人员</p>
            <div @click="clearAll">清空</div>
          </div>

          <div class="table-box">
            <el-table
              key="table-right"
              :data="multipleSelection"
              stripe
              style="width: 100%"
              :height="370"
              :header-cell-style="{
                background: '#F7F9FD',
                color: '#000',
                height: '40px',
                borderTop: '1px soild #E4E8F2'
              }"
              class="scrollBar"
            >
              <template #empty>
                <el-empty :image-size="150" description="暂无数据"></el-empty>
              </template>
              <el-table-column
                type="index"
                label="序号"
                width="50"
              ></el-table-column>
              <el-table-column
                prop="name"
                label="姓名"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="userName"
                label="用户名"
                show-overflow-tooltip
              ></el-table-column>

              <el-table-column label="操作" fixed="right">
                <template #default="{ row }">
                  <el-button type="text" class="btns-danger" @click="clear(row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form__footer">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  defineEmits,
  defineProps,
  reactive,
  nextTick,
  onMounted
} from "vue";
import { getUserList } from "/@/api/user";
import { getDeptTree } from "/@/api/projects";
import NotifMessage from "/@/utils/message/notification";
import RePagination from "/@/components/RePagination/index.vue";
const emit = defineEmits(["emitAddUser", "update:dialogVisibleTransferAdd"]);
const props = defineProps({
  currentUsers: {
    type: Array,
    default: () => []
  },
  isSingle: {
    type: Boolean,
    default: false,
    required: false
  }
});

let userList = ref([]);
let multipleSelection = ref([]);
let total = ref(0);
let formInline = reactive({
  nameLike: "",
  memoLike: "",
  pageNum: 1,
  pageSize: 10
});
const treeData = ref([]);
let defaultProps = {
  //树显示字段
  children: "children",
  label: "deptDescShrt"
};

const multipleTable = ref<HTMLElement | null>(null) as any;

const getRowKeys = row => {
  return row.id;
};

const handleSearch = () => {
  getUserLists(formInline);
};

const getUserLists = async (obj: object = {}) => {
  try {
    const { code, data } = await getUserList(obj);
    if (code === 200) {
      total.value = data.rows;
      userList.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name,
          userName: item.userName,
          userId: item.id,
          deptName: item.isEmp === "0" ? item.companyName : item.memo, // 外部用户取companyName
          deptCode: item.isEmp === "0" ? item.companyId : item.deptId,
          email: item.email,
          phoneNum: item.phoneNum
        };
      });
    }
  } catch (err) {
    console.log(err);
  } finally {
    multipleTable.value.doLayout();
  }
};

const handleSelectionChange = (val, row) => {
  if (props.isSingle && multipleSelection.value.length && val.length) {
    NotifMessage.info("只能选择一个人员");
    // 且将这个选中项取消
    multipleTable.value!.toggleRowSelection(row, undefined);
  } else {
    multipleSelection.value = val;
  }
};

const handleSelectionAll = val => {
  if (props.isSingle && val.length > 1) {
    NotifMessage.info("只能选择一个人员");
    // 且将这个选中项取消
    multipleTable.value!.clearSelection();
    multipleSelection.value = [];
  } else {
    multipleSelection.value = val;
  }
};

//批量清空所选人员
const clearAll = () => {
  multipleTable.value!.clearSelection();
  multipleSelection.value = [];
};

//单个清除所选人员
const clear = row => {
  multipleTable.value!.toggleRowSelection(row, undefined);
  multipleSelection.value = multipleSelection.value.filter(el => {
    return el.id !== row.id;
  });
};

getUserLists({
  pageNum: 1,
  pageSize: 10,
  nameLike: "",
  memoLike: ""
});

// const toggleSelection = rows => {
//   if (rows) {
//     rows.forEach(row => {
//       multipleTable.value.toggleRowSelection(row);
//     });
//   } else {
//     multipleTable.value.clearSelection();
//   }
// };
// -----------------------------------------

onMounted(() => {
  if (props.currentUsers && !multipleSelection.value.length) {
    nextTick(() => {
      props.currentUsers.forEach(row => {
        multipleTable.value.toggleRowSelection(row);
      });
      multipleSelection.value = props.currentUsers;
    });
  }
  getDeptTreeFunc();
});

const handleSubmit = async () => {
  const flterList = [];
  const idList = [];
  if (!multipleSelection.value.length) {
    NotifMessage.info("至少选择一个人员");
    return;
  }
  if (multipleSelection.value.length) {
    multipleSelection.value.forEach(item => {
      flterList.push(item.name);
      let obj = {
        id: item.id,
        name: item.name,
        userName: item.userName
      };
      idList.push(obj);
    });
  }
  emit("emitAddUser", {
    idList: idList,
    nameList: flterList.join(),
    infoList: multipleSelection.value
  });
  // 关闭弹出后清空数据
  multipleSelection.value = [];
  multipleTable.value!.clearSelection();
};

const handleCancel = () => {
  emit("update:dialogVisibleTransferAdd", false);
  // 关闭弹出后清空数据
  multipleSelection.value = [];
  multipleTable.value!.clearSelection();
  formInline.memoLike = "";
  getUserLists(formInline);
};

//获取组织关系
const getDeptTreeFunc = async () => {
  try {
    const { data } = await getDeptTree({});
    treeData.value = data || [];
    console.log(treeData.value, "48588");
  } catch (err) {
    console.log(err);
  }
};

// 节点单击事件
const handleNodeClick = data => {
  formInline.memoLike = data.deptDescShrt;
  getUserLists(formInline);
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;

  .form__footer {
    width: 100%;
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
.content-table {
  width: 100%;
  height: 100%;
  // border: 1px solid #e4e7ed;
  &--wrap {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    .table-box {
      // width: 380px;
      // border: 1px solid #e4e8f2;
      // border-bottom: none;
    }
    .user-tree:deep {
      width: 200px;
      height: 450px;
      border-radius: 4px;
      border: 1px solid #e4e8f2;
      overflow: scroll;
      .el-tree {
        overflow: visible !important;
      }
      .el-tree-node > .el-tree-node__children {
        overflow: visible !important;
      }
    }
    .table-left {
      width: 36%;
      .flex-box {
        font-size: 12px;
        padding: 8px 0 8px 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #495164;
        background: #fdfdff;
        border-radius: 4px 4px 0px 0px;
        border: 1px solid #e4e8f2;
        border-bottom: none;
      }
      &--header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
        i {
          color: #c2cade;
        }
        p {
          color: #495164;
          font-weight: bold;
          margin-left: 14px;
        }
      }
      &--btn {
        float: right;
      }
      &--footer {
        height: 28px;
        display: flex;
        justify-content: flex-end;
        margin-top: 9px;
        margin-bottom: 5px;
        .pagination-container {
          padding: 0;
        }
      }
    }
    .table-right {
      width: 40%;
      margin-top: 48px;
      border-radius: 4px;
      border: 1px solid #e4e8f2;
      &--header {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        justify-content: space-between;
        background: #fdfdff;
        font-weight: 500;
        color: #495164;
        i {
          color: #c2cade;
        }
        p {
          color: #495164;
          font-weight: bold;
          margin-left: 10px;
          font-size: 14px;
        }
        div {
          cursor: pointer;
          font-weight: 500;
          color: #5298ff;
        }
      }
    }
  }
}
// .content-table :deep .el-table__fixed-right-patch {
//   background: #eef1f6 !important;
// }

// .content-table :deep .el-table__header {
//   background: #F7F9FD !important;
//   // background: red !important;
// }

// .content-table :deep .el-table__header {
//   height: 40px;
// }
// .content-table :deep .el-table__row {
//   height: 40px;
// }
</style>
